﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace GameJamKingdom
{
    class AnimatedComponent
    {
        List<Texture2D> data;

        int totalImages;

        string folderName, baseName;

        float frameSpan;

        int timeSinceChange;
        int cFrame;

        bool isSpriteSheet;

        public AnimatedComponent(string fName, string bName, int numImages, float fRate, Game1 cGame)
        {
            totalImages = numImages;
            folderName = fName;
            baseName = bName;
            frameSpan = 1000/fRate;

            timeSinceChange = 0;
            cFrame = 0;

            isSpriteSheet = false;

            data = new List<Texture2D>();
            for (int i = 1; i <= numImages; i++)
            {
                string fullPath = fName + "/" + bName + i.ToString();
                Texture2D temp = cGame.Content.Load<Texture2D>(fullPath);
                data.Add(temp);
            }
        }

        public AnimatedComponent(string fName, int numImages, float fRate, Game1 cGame)
        {
            totalImages = numImages;
            folderName = fName;
            frameSpan = 1000 / fRate;

            timeSinceChange = 0;
            cFrame = 0;

            isSpriteSheet = true;

            data = new List<Texture2D>();
            Texture2D temp = cGame.Content.Load<Texture2D>(fName);
            data.Add(temp);
        }

        public void update(GameTime cTime)
        {
            timeSinceChange = timeSinceChange + cTime.ElapsedGameTime.Milliseconds;

            if (timeSinceChange > (int)frameSpan)
            {
                cFrame++;
                timeSinceChange = 0;
                if (cFrame >= totalImages)
                    cFrame = 0;
            }
        }

        public void render(Rectangle cRect, SpriteBatch spriteBatch)
        {
            if (!isSpriteSheet)
                spriteBatch.Draw(data[cFrame], cRect, Color.White);
            else
            {
                Rectangle sRect = new Rectangle((int)(cFrame * data[0].Width / totalImages), 0, (int)(data[0].Width / totalImages), data[0].Height);
                spriteBatch.Draw(data[0], cRect, sRect, Color.White);
            }
        }


    }
}
